<template>
	<view>
		<scroll-view id="chatRoom" ref="chatRoom" scroll-y="true" class="cu-chat" show-scrollbar="true"
			:style="'height:'+ contentHeight+'rpx'" :scroll-into-view="scrollIntoID" :refresher-threshold="45"
			:refresher-triggered="refresherTriggered" @refresherrefresh="refresherrefresh"
			@refresherrestore="refresherrestore" @refresherabort="refresherabort">
			<view style="overflow: auto;" id="message_box">
				<view v-for="(item,index) in messageList" :key="index" :id="'rowid_'+index" :ref="'rowid_'+index">
					<!-- 文本  自己右侧 -->
					<view class="cu-item self" v-if="item.uid==user.id&&item.msg_type==0">
						<view class="main">
							<view class="content bg-green shadow">
								<text>{{item.message}}</text>
							</view>
						</view>
						<view style="height: 100rpx;">
							<view style="font-size: 30rpx;">{{item.content.name}}</view>
							<view class="cu-avatar radius" @click="userImgClick(item)">
								<image class="cu-avatar radius" :src="item.content.header"></image>
							</view>
						</view>
						<!-- 	<view class="date">{{item.time}}</view> -->
					</view>
					<!-- 文本 左侧对方 -->

					<view class="cu-item" v-if="item.uid!=user.id&&item.msg_type==0">
						<view>
							<view style="font-size: 30rpx;">{{item.content.name}}</view>
							<view class="cu-avatar radius" @click="serImgClick(item)">
								<image class="cu-avatar radius" :src="item.content.header"></image>
							</view>
						</view>
						<view class="main">
							<view class="content shadow">
								<text>{{item.message}}</text>
							</view>
						</view>
						<!-- <view class="date "> {{item.time}}</view> -->
					</view>
					<!-- 图片  自己右侧 -->
					<view class="cu-item self" v-if="item.uid==user.id&&item.msg_type==1">
						<view>
							<view style="float: right;">
								<view style="font-size: 30rpx;">{{item.content.name}}</view>
								<view class="cu-avatar radius" @click="userImgClick(item)">
									<image class="cu-avatar radius" :src="item.content.header"></image>
								</view>
							</view>
							<view class="main" @click="imagePreviewClick(item)" style="float: left;">
								<image style="width: 200rpx;height: 200rpx;" :src="api_url+item.url" class="radius"
									mode="widthFix"></image>
							</view>

						</view>


						<!-- <view class="date"> {{item.time}}</view> -->
					</view>
					<!-- 图片 左侧对方 -->
					<view class="cu-item" v-if="item.uid!=user.id&&item.msg_type==1">

						<view>
							<view style="font-size: 30rpx;">{{item.content.name}}</view>
							<view class="cu-avatar radius" @click="userImgClick(item)">
								<image class="cu-avatar radius" :src="item.content.header"></image>
							</view>
						</view>

						<view class="main" @click="imagePreviewClick(item)">
							<image style="width: 200rpx;height: 200rpx;" :src="api_url+item.url" class="radius"
								mode="widthFix"></image>
						</view>

						<!-- <view class="date"> {{item.time}}</view> -->
					</view>
				</view>
			</view>
		</scroll-view>

		<view class="cu-bar foot input" :style="[{bottom:InputBottom+'px'}]"
			style="position: fixed;bottom: 0;left: 0;width: 100%;background-color:#DBF1E1;">
			<input class="solid-bottom" style="background-color: #FFFFFF;border-radius: 10rpx;" :adjust-position="false"
				:focus="false" maxlength="300" v-model="inputText" cursor-spacing="10" @focus="InputFocus"
				@blur="InputBlur"></input>
			<view class="action">
				<!-- <text class="cuIcon-record text-grey" @click="recordVideoClick"></text> -->
				<text class="cuIcon-pic text-grey" @click="chooseImageClick"></text>
				<!-- <text class="cuIcon-emojifill text-grey"></text> -->
			</view>
			<button class="cu-btn bg-green shadow" style="margin-right: 30rpx;" @tap="sendClick(0)">发送</button>
		</view>
	</view>
</template>

<script>
	var _self
	var socket = null;

	import {
		Socket_url
	} from '../../common/config.js'
	import {Api_url} from '@/common/config.js'
	export default {

		data() {
			return {
				isRecordingMode: false, //是否录音模式
				isLoading: false,
				targetItem: {
					EncryptID: ""
				}, //对方用户的信息，包括
				contentHeight: "",
				currentPageCount: 0, //用来定位页数显示，当前页数得到的数据个数
				refresherTriggered: false,
				pageIndex: 0,
				get_img: this.$get_img,
				api_url:Api_url,
				inputText: '',
				dataItem: {},
				ChatItem: {},
				InputBottom: 0,
				messageList: [],
				title: "",
				scrollIntoID: "",
				videolist: [],
				imgList: [], //发送的临时图片列表
				soundlist: [], //发送的声音文件列表
				voicetime: 0, //录音的时间
				recordTimer: {}, //录音计时器
				isRecording: false, //是否正在录音
				isVoiceButtonShow: true, //是否显示录音按钮
				recordingStartY: 0, //录音开始的Y
				recordingCancelSpace: 100, //滑动取消录音的距离
				isRecordingCanceling: false, //是否正在取消，显示取消发送
				voicePath: '',
				user: {},
				talking_group: {},
				text_length: 0,
				custom_id: '',
				content: {},
				file_url: "",
				user_type: "",
				page: 1,
				message_id: "",
				num: 10,
				is_reach: false
			};
		},
		onPullDownRefresh() {
			console.log("pull")
			this.page++
			this.get_data()
		},
		onLoad(option) {
			let that = this
			if (option.id) {
				this.custom_id = option.id
			} else {
				uni.showToast({
					title: "客户繁忙"
				})
				setTimeout(function() {
					uni.navigateBack({

					})
				}, 1000)
			}
			this.user = uni.getStorageSync('infor')
			if (option.user_type) {
				this.user_type = "custom"
				this.message_id = this.custom_id + "_" + this.user.id + "_talking"
			} else {
				this.user_type = "user"
				this.message_id = this.user.id + "_" + this.custom_id + "_talking"
			}
			uni.connectSocket({
				url: Socket_url
			});
			uni.onSocketOpen(function(res) {
				console.log('WebSocket连接已打开！');
				that.login()
			});
			uni.onSocketError(function(res) {
				uni.showToast({
					title: "系统错误，请重试"
				})
			});
			
			//带有on的监听



			uni.onSocketMessage(function(res) {
				that.get_socket_data(res)
			});
			this.get_data()



			let self = this;
			this.contentHeight = uni.getSystemInfoSync().screenHeight * 2;
			_self = this



		},
		onUnload() {
			uni.closeSocket();
		},
		mounted() {
			//this.scrollToBottom()
		},
		updated() {

		},
		methods: {
			login() {
				let data = {
					type: "login",
					user: this.user,
					id: this.user.id,
					cid: this.custom_id,
					user_type: this.user_type,
					token: uni.getStorageSync("token")
				}
				this.send_msg(data)
			},
			send_msg(data) {
				data = JSON.stringify(data)
				uni.sendSocketMessage({
					data: data
				});
			},
			get_socket_data(res) {
				let message = JSON.parse(res.data)
				console.log(message)
				switch (message.type) {
					case "login_res":
						this.content = message.content
						uni.setNavigationBarTitle({
							title: this.content.name
						})
						break;
					case "msg_reg":
						this.messageList.push(message.data)
						break;
				}
				this.scrollToBottom()
			},
			//0文本  1图片 2视频
			sendClick(type = 0) {
				var myDate = new Date();
				let content = {
					id: this.user.id,
					name: this.user.nickname,
					header: this.user.avatar
				}
				let message = {
					content: content,
					type: "send_message",
					msg_type: type,
					message: this.inputText,
					url: this.file_url,
					cid: this.custom_id
				}
				console.log("send_message", message)

				this.send_msg(message)
				this.inputText = ''
				this.file_url = ""

			},
			get_data() {
				let that = this
				this.$model.get("user/get_message?page=" + this.page + "&num=" + this.num + "&message_id=" + this
					.message_id).then(res => {
					if (res.code == 200) {
						if (res.data.data.length != 0) {
							res.data.data.forEach(function(value) {
								that.messageList.unshift(value)
							})
							console.log(that.messageList)
						} else {
							that.is_reach = true
						}
						that.scrollToBottom()
					}
				})
			},
			group_talking(data) {
				_self.messageList.push(data)
				console.log(data)
				/* if(_self.messageList.length>1)
					this.scrollToBottom() */

			},
			custom_infor(data) {
				this.talking_group = data.group
				uni.setNavigationBarTitle({
					title: data.manage_name
				})
				let message = {
					template: 1,
					photoUrl: this.$get_img + "/system/custom.png",
					Message: "您好，" + data.manage_name + " 为您服务",
					time: data.time
				}
				this.messageList.push(message)
			},
			scrollToBottom() {
				const res = uni.getSystemInfoSync();

				let pageHeight = res.windowHeight;
				const query = uni.createSelectorQuery().in(this);
				query.select('#chatRoom').boundingClientRect(data => {
					console.log("得到布局位置信息", data);
					console.log("节点离页面顶部的距离为" + data.top);
				}).exec();
				this.text_length = 0
				let that = this
				for (let i = 0; i < this.messageList.length; i++) {
					query.select('#rowid_' + i).boundingClientRect(data => {
						if (data) {
							that.text_length += data.height
							uni.pageScrollTo({
								scrollTop: that.text_length,
								selector: '#chatRoom'
							})

						}
					}).exec();
				}
				this.scrollIntoID = "rowid_" + (this.messageList.length - 1);
			},
			custom_infor_error(data) {
				let message = {
					template: 1,
					photoUrl: '../../static/chat/custom.png',
					Message: data.msg,
					time: data.time
				}
				_self.messageList.push(message)
			},

			soundClick(item) {


			},
			//键盘和语音切换
			recordInputClick() {
				this.isRecordingMode = !this.isRecordingMode;
			},
			//点击查看单个图片
			imagePreviewClick(item) {


			},
			videoPlayClick(item) {

			},
			userImgClick(item) {


			},
			refresherrefresh() {

			},
			refresherrestore() {

			},
			refresherabort() {

			},
			// 点击图片上传
			chooseImageClick() {
				let that = this
				uni.chooseImage({
					count: 1, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album', 'camera'], //从相册选择
					success: (chooseImageRes) => {
						const tempFilePaths = chooseImageRes.tempFilePaths;
						console.log(tempFilePaths[0], chooseImageRes);
						uni.uploadFile({
							url: that.api_url + 'user/common/uploads_image', //仅为示例，非真实的接口地址
							filePath: tempFilePaths[0],
							name: 'img',
							success: (uploadFileRes) => {

								let data = uploadFileRes.data
								data = JSON.parse(data)
								console.log(data)
								that.file_url = data.data.url
								that.sendClick(1)
								/*	console.log(data);
									let message = { 
										template: 2,
										photoUrl: that.user.headpic,
										Message: data.data.path,
										type: 'send_message',
										talking_group: that.talking_group
									}
									that.$socket.dispatch('websoketSend', message) */
							}
						});
					}
				});
			},

			InputFocus(e) {
				this.InputBottom = e.detail.height
			},
			InputBlur(e) {
				this.InputBottom = 0
			},
			getTemplateByMessageType(messageType, fromUserID) {

			}
		}
	}
</script>

<style lang="scss">
	@import "@/colorui/main.css";

	page {
		padding-bottom: 100upx;
	}

	.uni-canvas {
		width: auto;
		/* height: auto; */
	}

	.bg-topic-theme {
		background-color: #F8D347;
		color: #333333;
	}

	* {
		-webkit-touch-callout: none;
		-webkit-user-select: none;
		-khtml-user-select: none;
		-moz-user-select: none;
		-ms-user-select: none;
		user-select: none;
	}

	.solid-bottom::after {
		border-bottom: 1upx solid rgba(0, 0, 0, 0.1);
	}

	.cu-bar {
		display: flex;
		position: relative;
		align-items: center;
		min-height: 100upx;
		justify-content: space-between;
	}

	.cu-bar .action {
		display: flex;
		align-items: center;
		height: 100%;
		justify-content: center;
		max-width: 100%;
	}

	.cu-bar .action.border-title {
		position: relative;
		top: -10upx;
	}

	.cu-bar .action.border-title text[class*="bg-"]:last-child {
		position: absolute;
		bottom: -0.5rem;
		min-width: 2rem;
		height: 6upx;
		left: 0;
	}

	.cu-bar .action.sub-title {
		position: relative;
		top: -0.2rem;
	}

	.cu-bar .action.sub-title text {
		position: relative;
		z-index: 1;
	}

	.cu-bar .action.sub-title text[class*="bg-"]:last-child {
		position: absolute;
		display: inline-block;
		bottom: -0.2rem;
		border-radius: 6upx;
		width: 100%;
		height: 0.6rem;
		left: 0.6rem;
		opacity: 0.3;
		z-index: 0;
	}

	.cu-bar .action.sub-title text[class*="text-"]:last-child {
		position: absolute;
		display: inline-block;
		bottom: -0.7rem;
		left: 0.5rem;
		opacity: 0.2;
		z-index: 0;
		text-align: right;
		font-weight: 900;
		font-size: 36upx;
	}

	.cu-bar.justify-center .action.border-title text:last-child,
	.cu-bar.justify-center .action.sub-title text:last-child {
		left: 0;
		right: 0;
		margin: auto;
		text-align: center;
	}

	.cu-bar .action:first-child {
		margin-left: 30upx;
		font-size: 30upx;
	}

	.cu-bar .action1:first-child {
		margin-left: 0upx !important;
		font-size: 30upx !important;
	}

	.cu-bar .action text.text-cut {
		text-align: left;
		width: 100%;
	}

	.cu-bar .cu-avatar:first-child {
		margin-left: 20upx;
	}

	.cu-bar .action:first-child>text[class*="cuIcon-"] {
		margin-left: -0.3em;
		margin-right: 0.3em;
	}

	.cu-bar .action:last-child {
		margin-right: 30upx;
	}

	.cu-bar .action>text[class*="cuIcon-"],
	.cu-bar .action>view[class*="cuIcon-"] {
		font-size: 36upx;
	}

	.cu-bar .action>text[class*="cuIcon-"]+text[class*="cuIcon-"] {
		margin-left: 0.5em;
	}

	.cu-bar .content {
		position: absolute;
		text-align: center;
		width: calc(100% - 340upx);
		left: 0;
		right: 0;
		bottom: 0;
		top: 0;
		margin: auto;
		height: 60upx;
		font-size: 32upx;
		line-height: 60upx;
		cursor: none;
		pointer-events: none;
		text-overflow: ellipsis;
		white-space: nowrap;
		overflow: hidden;
	}

	.cu-bar.ios .content {
		bottom: 7px;
		height: 30px;
		font-size: 32upx;
		line-height: 30px;
	}

	.cu-bar.btn-group {
		justify-content: space-around;
	}

	.cu-bar.btn-group button {
		padding: 20upx 32upx;
	}

	.cu-bar.btn-group button {
		flex: 1;
		margin: 0 20upx;
		max-width: 50%;
	}

	.cu-bar .search-form {
		background-color: #f5f5f5;
		line-height: 64upx;
		height: 64upx;
		font-size: 24upx;
		color: #333333;
		flex: 1;
		display: flex;
		align-items: center;
		margin: 0 30upx;
	}

	.cu-bar .search-form+.action {
		margin-right: 30upx;
	}

	.cu-bar .search-form input {
		flex: 1;
		padding-right: 30upx;
		height: 64upx;
		line-height: 64upx;
		font-size: 26upx;
		background-color: transparent;
	}

	.cu-bar .search-form [class*="cuIcon-"] {
		margin: 0 0.5em 0 0.8em;
	}

	.cu-bar .search-form [class*="cuIcon-"]::before {
		top: 0upx;
	}

	.cu-bar.fixed,
	.nav.fixed {
		position: fixed;
		width: 100%;
		top: 0;
		z-index: 1024;
		box-shadow: 0 1upx 6upx rgba(0, 0, 0, 0.1);
	}

	.cu-bar.foot {
		position: fixed;
		width: 100%;
		bottom: 0;
		z-index: 1024;
		box-shadow: 0 -1upx 6upx rgba(0, 0, 0, 0.1);
	}

	.cu-btn {
		position: relative;
		border: 0upx;
		display: inline-flex;
		align-items: center;
		justify-content: center;
		box-sizing: border-box;
		padding: 0 30upx;
		font-size: 28upx;
		height: 64upx;
		line-height: 1;
		text-align: center;
		text-decoration: none;
		overflow: visible;
		margin-left: initial;
		transform: translate(0upx, 0upx);
		margin-right: initial;
	}

	.cu-btn::after {
		display: none;
	}

	.cu-btn:not([class*="bg-"]) {
		background-color: #f0f0f0;
	}

	.cu-btn[class*="line"] {
		background-color: transparent;
	}

	.cu-btn[class*="line"]::after {
		content: " ";
		display: block;
		width: 200%;
		height: 200%;
		position: absolute;
		top: 0;
		left: 0;
		border: 1upx solid currentColor;
		transform: scale(0.5);
		transform-origin: 0 0;
		box-sizing: border-box;
		border-radius: 12upx;
		z-index: 1;
		pointer-events: none;
	}

	.cu-btn.round[class*="line"]::after {
		border-radius: 1000upx;
	}

	.cu-btn[class*="lines"]::after {
		border: 6upx solid currentColor;
	}

	.cu-btn[class*="bg-"]::after {
		display: none;
	}

	.cu-btn.sm {
		padding: 0 20upx;
		font-size: 20upx;
		height: 48upx;
	}

	.cu-btn.lg {
		padding: 0 40upx;
		font-size: 32upx;
		height: 80upx;
	}

	.cu-btn.cuIcon.sm {
		width: 48upx;
		height: 48upx;
	}

	.cu-btn.cuIcon {
		width: 64upx;
		height: 64upx;
		border-radius: 500upx;
		padding: 0;
	}

	button.cuIcon.lg {
		width: 80upx;
		height: 80upx;
	}

	.cuIcon-sound:before {
		content: "\e77b";
	}

	.cu-btn.shadow-blur::before {
		top: 4upx;
		left: 4upx;
		filter: blur(6upx);
		opacity: 0.6;
	}

	.cu-btn.button-hover {
		transform: translate(1upx, 1upx);
	}

	.block {
		display: block;
	}

	.cu-btn.block {
		display: flex;
	}

	.cu-btn[disabled] {
		opacity: 0.6;
		color: #ffffff;
	}

	.bg-green {
		background-color: #39b54a;
		color: #ffffff;
	}

	.bg-green.light {
		color: #39b54a;
		background-color: #d7f0dbff;
	}

	.shadow[class*='white'] {
		--ShadowSize: 0 1upx 6upx;
	}
</style>
